package edu.pku.hawk.controller.util;

import edu.pku.hawk.controller.util.Constants.FusionAlgorithm;
import edu.pku.hawk.service.FusionSer;
import edu.pku.hawk.service.SensorDataSer;
import edu.pku.hawk.service.impl.FusionSerImpl_Average;
import edu.pku.hawk.service.impl.FusionSerImpl_Emulation;
import edu.pku.hawk.service.impl.SensorDataSerImpl_Local;

public class ServiceManager {

	MQManager mgr;
	SensorDataSer sensorDataSer;
	FusionSer fusionSer;

	public ServiceManager(MQManager mgr) {
		this.mgr = mgr;
		sensorDataSer = new SensorDataSerImpl_Local();

		if (Config.FusionImpl == FusionAlgorithm.Average) {
			fusionSer = new FusionSerImpl_Average();
		} else if (Config.FusionImpl == FusionAlgorithm.MatlabEmulation) {
			fusionSer = new FusionSerImpl_Emulation();
		}
	}

	public SensorDataSer getSensorDataSer() {
		return sensorDataSer;
	}

	public FusionSer getFusionSer() {
		return fusionSer;
	}

	public SerResourceList connectService(ProcDes pdes) {
		SerResourceList send = new SerResourceList(Config.Singleton.Instance.getSerRscMapByType(), pdes.detectorTypes);
		send.setCjName(pdes.scenarioName);
		
		for(int i=0; i<pdes.detectorTypes.length; i++) {
			send.ResourceList.get(i).setClientURI(pdes.clientIP);
		}
		SerResourceList receive = null;
		if (Config.ResourceRequest == true) {
			try {
				Util.log("Send resource request to cloud... ");
				MProducerQueue pq = mgr.getProducerQueue(Constants.Ctrl_Cloud_RscRequest_QueueName);
				pq.send(send);
				Util.logln("Down.");

				// Wait
				Util.log("Waiting resourcd response from cloud... ");
				MConsumerQueue cq = mgr.getConsumerQueue(Constants.Ctrl_Cloud_RscResponse_QueueName);
				receive = (SerResourceList) cq.getObject();
				Util.logln("Down");
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			receive = send;
		}
		return receive;
	}

}
